package cn.jiaqiang.chatgpt.data.domain.openai.service.chat;

import cn.jiaqiang.chatgpt.data.domain.openai.model.aggregates.ChatProcessAggregate;
import cn.jiaqiang.chatgpt.data.domain.openai.model.entity.RuleLogicEntity;
import cn.jiaqiang.chatgpt.data.domain.openai.model.entity.UserAccountEntity;
import cn.jiaqiang.chatgpt.data.domain.openai.model.valobj.LogicCheckTypeVO;
import cn.jiaqiang.chatgpt.data.domain.openai.service.channel.OpenAiGroupService;
import cn.jiaqiang.chatgpt.data.domain.openai.service.channel.impl.ChatGLMService;
import cn.jiaqiang.chatgpt.data.domain.openai.service.channel.impl.ChatGPTService;
import cn.jiaqiang.chatgpt.data.domain.openai.service.rule.ILogicFilter;
import cn.jiaqiang.chatgpt.data.domain.openai.service.rule.factory.DefaultLogicFactory;
import cn.jiaqiang.chatgpt.data.types.enums.OpenAiChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @description 聊天实现
 */
@Slf4j
@Service
public class UserChatService {

    protected final Map<OpenAiChannel, OpenAiGroupService> openAiGroup = new HashMap<>();

    public UserChatService(ChatGPTService chatGPTService, ChatGLMService chatGLMService) {
        openAiGroup.put(OpenAiChannel.ChatGPT, chatGPTService);
        openAiGroup.put(OpenAiChannel.ChatGLM, chatGLMService);
    }

    @Resource
    private DefaultLogicFactory logicFactory;

    protected RuleLogicEntity<ChatProcessAggregate> doCheckLogic(ChatProcessAggregate chatProcess,
                                                                 UserAccountEntity data, String... logics) throws Exception {
        Map<String, ILogicFilter<UserAccountEntity>> logicFilterMap = logicFactory.openLogicFilter();
        RuleLogicEntity<ChatProcessAggregate> entity = null;
        for (String logic : logics) {

            // 不能直接对 data 进行判空, 因为未开户的用户 data 也是空.
            if (logic == null) {
                continue;
            }
            log.info("用户 userId {} 进行 {} 过滤.", chatProcess.getUserId(), logic);
            ILogicFilter<UserAccountEntity> iLogicFilter = logicFilterMap.get(logic);
            entity = iLogicFilter.filter(chatProcess, data);

            if (!LogicCheckTypeVO.SUCCESS.equals(entity.getType())) {
                return entity;
            }
        }
        // entity == null is true -> 不进行过滤, 返回 LogicCheckTypeVO.SUCCESS
        // entity != null is true -> 直接返回, 进行 chatgpt 问答 (敏感词过滤都是返回 LogicCheckTypeVO.SUCCESS 的)
        return entity != null ? entity :
                RuleLogicEntity
                        .<ChatProcessAggregate>builder()
                        .type(LogicCheckTypeVO.SUCCESS)
                        .data(chatProcess)
                        .build();
    }

}
